<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <ContentWrap>
      <el-row :gutter="20" class="mb-20px">
        <el-col :span="24">
          <div class="page-header">
            <div class="header-left">
              <el-icon size="24" color="#409EFF">
                <ep-user />
              </el-icon>
              <h2 class="page-title">用户管理</h2>
            </div>
            <el-tag type="info">小程序管理模块</el-tag>
          </div>
        </el-col>
      </el-row>
    </ContentWrap>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-20px">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon primary">
              <el-icon size="24"><ep-user /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon success">
              <el-icon size="24"><ep-user-filled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ activeUsers }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon warning">
              <el-icon size="24"><ep-calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ todayNewUsers }}</div>
              <div class="stat-label">今日新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon danger">
              <el-icon size="24"><ep-warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ blockedUsers }}</div>
              <div class="stat-label">封禁用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <ContentWrap>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入用户昵称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="正常" value="normal" />
            <el-option label="封禁" value="blocked" />
            <el-option label="注销" value="deleted" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><ep-search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><ep-refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 操作栏 -->
    <ContentWrap>
      <div class="mb-20px">
        <el-button type="success" @click="handleExport">
          <el-icon><ep-download /></el-icon>
          导出数据
        </el-button>
        <el-button type="warning" @click="handleBatchBlock" :disabled="!multipleSelection.length">
          <el-icon><ep-warning /></el-icon>
          批量封禁
        </el-button>
        <el-button type="info" @click="handleSendMessage" :disabled="!multipleSelection.length">
          <el-icon><ep-message /></el-icon>
          发送消息
        </el-button>
      </div>
    </ContentWrap>

    <!-- 数据表格 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="50">
              <el-icon><ep-user /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="mobile" label="手机号" width="130" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 'male' ? 'primary' : 'danger'" size="small">
              {{ row.gender === 'male' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="readCount" label="阅读次数" width="100" />
        <el-table-column prop="favoriteCount" label="收藏数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              :type="row.status === 'blocked' ? 'success' : 'warning'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'blocked' ? '解封' : '封禁' }}
            </el-button>
            <el-button type="info" size="small" @click="handleMessage(row)">
              消息
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 示例说明 -->
    <ContentWrap>
      <el-alert
        title="功能说明"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <p><strong>用户管理功能包括：</strong></p>
          <ul>
            <li>👥 用户信息管理：查看用户基本信息、阅读记录、收藏记录等</li>
            <li>📊 数据统计：显示总用户数、活跃用户、今日新增、封禁用户等统计信息</li>
            <li>🔍 搜索筛选：支持按昵称、手机号、状态、注册时间等条件筛选</li>
            <li>⚡ 用户操作：支持封禁/解封用户、发送系统消息等</li>
            <li>📤 数据导出：支持导出用户数据为Excel文件</li>
            <li>💬 消息推送：支持向用户发送系统消息和通知</li>
          </ul>
        </template>
      </el-alert>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'MiniprogramUserManage' })

// 响应式数据
const loading = ref(false)
const total = ref(0)
const userList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

// 统计数据
const totalUsers = ref(12580)
const activeUsers = ref(8960)
const todayNewUsers = ref(156)
const blockedUsers = ref(23)

// 查询参数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  nickname: '',
  mobile: '',
  status: '',
  dateRange: null
})

// 获取状态标签
const getStatusLabel = (status: string) => {
  const map = {
    'normal': '正常',
    'blocked': '封禁',
    'deleted': '注销'
  }
  return map[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const map = {
    'normal': 'success',
    'blocked': 'danger',
    'deleted': 'info'
  }
  return map[status] || 'info'
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    userList.value = [
      {
        id: 10001,
        nickname: '小明妈妈',
        mobile: '138****1234',
        avatar: 'https://picsum.photos/100/100?random=1',
        gender: 'female',
        readCount: 156,
        favoriteCount: 23,
        status: 'normal',
        lastLoginTime: formatDate(new Date(Date.now() - 3600000)),
        registerTime: formatDate(new Date(Date.now() - 86400000 * 30))
      },
      {
        id: 10002,
        nickname: '爱读书的爸爸',
        mobile: '139****5678',
        avatar: 'https://picsum.photos/100/100?random=2',
        gender: 'male',
        readCount: 89,
        favoriteCount: 12,
        status: 'normal',
        lastLoginTime: formatDate(new Date(Date.now() - 7200000)),
        registerTime: formatDate(new Date(Date.now() - 86400000 * 15))
      },
      {
        id: 10003,
        nickname: '小花的妈妈',
        mobile: '136****9012',
        avatar: 'https://picsum.photos/100/100?random=3',
        gender: 'female',
        readCount: 234,
        favoriteCount: 45,
        status: 'blocked',
        lastLoginTime: formatDate(new Date(Date.now() - 86400000 * 3)),
        registerTime: formatDate(new Date(Date.now() - 86400000 * 60))
      }
    ]
    total.value = 3
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    nickname: '',
    mobile: '',
    status: '',
    dateRange: null
  }
  getList()
}

// 查看用户详情
const handleView = (row: any) => {
  ElMessage.success(`查看用户详情：${row.nickname}`)
}

// 切换用户状态
const handleToggleStatus = async (row: any) => {
  const action = row.status === 'blocked' ? '解封' : '封禁'
  try {
    await ElMessageBox.confirm(`确定要${action}用户"${row.nickname}"吗？`, `确认${action}`, {
      type: 'warning'
    })
    ElMessage.success(`${action}成功`)
    getList()
  } catch {
    ElMessage.info(`取消${action}`)
  }
}

// 发送消息
const handleMessage = (row: any) => {
  ElMessage.success(`向用户"${row.nickname}"发送消息`)
}

// 导出数据
const handleExport = () => {
  ElMessage.success('开始导出用户数据')
}

// 批量封禁
const handleBatchBlock = async () => {
  try {
    await ElMessageBox.confirm(`确定要封禁选中的 ${multipleSelection.value.length} 个用户吗？`, '确认封禁', {
      type: 'warning'
    })
    ElMessage.success('批量封禁成功')
    getList()
  } catch {
    ElMessage.info('取消封禁')
  }
}

// 批量发送消息
const handleSendMessage = () => {
  ElMessage.success(`向 ${multipleSelection.value.length} 个用户发送消息`)
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.primary {
  background: linear-gradient(135deg, #409EFF, #66B3FF);
}

.stat-icon.success {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.stat-icon.danger {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}
</style>
